import { NextResponse } from 'next/server';
import { PrismaClient, GameMode } from '@prisma/client';

const prisma = new PrismaClient();

// 添加玩家分数
export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const playerId = parseInt(params.id);
    
    if (isNaN(playerId)) {
      return NextResponse.json(
        { error: '无效的玩家ID' },
        { status: 400 }
      );
    }
    
    // 检查玩家是否存在
    const player = await prisma.player.findUnique({
      where: { id: playerId }
    });
    
    if (!player) {
      return NextResponse.json(
        { error: '玩家不存在' },
        { status: 404 }
      );
    }
    
    const { mode, value } = await request.json();
    
    // 验证游戏模式
    if (!Object.values(GameMode).includes(mode as GameMode)) {
      return NextResponse.json(
        { error: '无效的游戏模式' },
        { status: 400 }
      );
    }
    
    // 创建分数记录
    const score = await prisma.score.create({
      data: {
        mode: mode as GameMode,
        value,
        playerId
      }
    });
    
    // 根据游戏模式更新玩家段位
    let tierUpdate = {};
    
    switch (mode) {
      case 'SWORD':
        tierUpdate = { swordTier: calculateTierFromScore(value) };
        break;
      case 'CRYSTAL':
        tierUpdate = { crystalTier: calculateTierFromScore(value) };
        break;
      case 'BUHC':
        tierUpdate = { buhcTier: calculateTierFromScore(value) };
        break;
      case 'POTION':
        tierUpdate = { potionTier: calculateTierFromScore(value) };
        break;
      case 'NPOT':
        tierUpdate = { npotTier: calculateTierFromScore(value) };
        break;
      case 'SMP':
        tierUpdate = { smpTier: calculateTierFromScore(value) };
        break;
    }
    
    // 如果需要更新段位，则更新玩家记录
    if (Object.keys(tierUpdate).length > 0) {
      await prisma.player.update({
        where: { id: playerId },
        data: tierUpdate
      });
    }
    
    return NextResponse.json({
      success: true,
      score: {
        ...score,
        id: score.id.toString(),
        playerId: score.playerId.toString()
      }
    });
  } catch (error) {
    console.error('添加分数失败:', error);
    return NextResponse.json(
      { error: '添加分数失败' },
      { status: 500 }
    );
  }
}

// 获取玩家所有分数
export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const playerId = parseInt(params.id);
    
    if (isNaN(playerId)) {
      return NextResponse.json(
        { error: '无效的玩家ID' },
        { status: 400 }
      );
    }
    
    // 检查玩家是否存在
    const player = await prisma.player.findUnique({
      where: { id: playerId }
    });
    
    if (!player) {
      return NextResponse.json(
        { error: '玩家不存在' },
        { status: 404 }
      );
    }
    
    // 获取分数记录
    const scores = await prisma.score.findMany({
      where: { playerId },
      orderBy: { createdAt: 'desc' }
    });
    
    const formattedScores = scores.map(score => ({
      ...score,
      id: score.id.toString(),
      playerId: score.playerId.toString()
    }));
    
    return NextResponse.json(formattedScores);
  } catch (error) {
    console.error('获取分数失败:', error);
    return NextResponse.json(
      { error: '获取分数失败' },
      { status: 500 }
    );
  }
}

// 根据分数计算段位函数
function calculateTierFromScore(score: number): number {
  if (score >= 500) return 1;
  if (score >= 300) return 2;
  if (score >= 150) return 3;
  if (score >= 50) return 4;
  return 5;
} 